package com.sxkiler.demo.utils;

import cn.hutool.core.util.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LogUtil {
    public static Logger logger = LoggerFactory.getLogger(LogUtil.class);
    public static ConcurrentHashMap<String, Map> logMaps = new ConcurrentHashMap<String, Map>();
    public static void startTransaction(){
        Map logMap = getThreadLogMap();
        logMap.put("traceId", RandomUtil.randomString(16));
        logMap.put("startTime",System.currentTimeMillis());
        logger.info("请求开始,{}",logMap);
    }
    public static Map getThreadLogMap(){
        Thread thread = Thread.currentThread();
        String threadId =  String.valueOf(thread.getId());
        Map logMap = logMaps.get(threadId);
        if(logMap==null){
            logMap = new HashMap();
            logMaps.put(threadId,logMap);
        }
        return logMap;
    }

    public static void clearContext(){
        Thread thread = Thread.currentThread();
        String threadId =  String.valueOf(thread.getId());
        logMaps.remove(threadId);
    }
    public static void setContext(String key,Object value){
        Map logMap = getThreadLogMap();
        logMap.put(key,value);
    }
    public static void endTransaction(){
        Map logMap = getThreadLogMap();
        if(logMap.get("startTime")!=null){
            long startTime = (long)logMap.get("startTime");
            long execTime = System.currentTimeMillis() - startTime;
            logMap.put("execTime",execTime);
        }
        logger.info("请求结束,{}",logMap);
    }
}
